import { useCallback } from "react";
import { DynamicCrudPage } from "@/components";
import type { TableConfig } from "@/components/DynamicTable/types";
import { getTableConfigByCode } from "@/api/tableConfig";
import { transformTableConfig } from "@/utils/tableConfigTransform";
import { transformEditData, transformSubmitData } from "@/utils/formDataTransform";
import {getUsers,createUser, updateUser,deleteUser, batchDeleteUsers, getUsersExportData,batchImportUsers,getImportTemplate} from "./api";

const UserManagement = () => {
  const fetchConfigApi = useCallback(async (): Promise<TableConfig> => {
    const configRecord = await getTableConfigByCode('users');
    if (!configRecord) {throw new Error('抛出错误，表格配置不存在');}
    return transformTableConfig(configRecord);
  }, []);

  const wrappedUpdateApi = async (data: any) => {
    const { id, ...updateData } = data;
    return updateUser(id, updateData);
  };

  // 包装 transformSubmitData 以匹配 DynamicCrudPage 的接口
  const handleTransformFormData = (data: any, mode: 'create' | 'update') => {
    return transformSubmitData(data);
  };

  return (
    <DynamicCrudPage
      fetchConfigApi={fetchConfigApi}
      fetchApi={getUsers}
      createApi={createUser}
      updateApi={wrappedUpdateApi}
      deleteApi={deleteUser}
      batchDeleteApi={batchDeleteUsers}
      exportApi={getUsersExportData}
      importApi={batchImportUsers}
      templateApi={getImportTemplate}
      transformEditData={transformEditData}
      transformFormData={handleTransformFormData}
      title="用户管理"
    />
  );
};

export default UserManagement;
